/*
 * @Author: mikey.zhaopeng
 * @Date:   2016-05-26 17:35:55
 * @Last Modified by:   mikey.zhaopeng
 * @Last Modified time: 2016-07-13 16:16:43
 */

'use strict';
define([
    '../../../framework/base/baseView',
    '../../../framework/bean/ecCreativeTemplate',
    'text!../tpl/saveDialog.html',
    'select2Source'
], function(
    BaseView,
    ecCreativeTemplateBean,
    tpl
) {
    function me() {
        BaseView.apply(this, arguments);
        var self = this;
        /**
         * { function_description }
         *
         * @param      {Function}  callback    The callback
         * @param      {<type>}    dialogParams  dialogParams  包含  预览图片URL,创建类型,名称等
         */
        this.init = function(callback, dialogParams) {
            self.callback = callback;
            self.dialogParams = dialogParams;
            self.$root = $('#create-material-save-dialog');
            self.render();
        }

        this.render = function() {
            self.$root.empty();
            self.$root.html(I18N.parse(tpl,'createMaterial'));
            self.$root.find('.preview-thumbnail .thumbnail img').attr('src', self.dialogParams.previewImg);
            var name = $('.layout-right').data('name');

            if (!self.kit.isBlank(name)) {
                var urlType = self.kit.getUrlParam('type');
                if (urlType != 'edit') {
                    self.$root.find('input[name=creativeName]').val(name +self.i18n('copy'));
                } else {
                    self.$root.find('input[name=creativeName]').val(name);
                    self.$root.find('input[name=creativeName]').data('old-name', name); //原始值
                }
            }
            self.$root.find('select.creativeTags').select2Source({
                tags: true
            });
            self.event();
            self.$root.modal('show');
        }

        this.event = function() {
            self.$root.find('.btn-ok').off('click').on('click', $.proxy(self.save, self));
        }

        this.save = function(e) {
            var urlType = self.kit.getUrlParam('type');
            var name = self.$root.find('input[name=creativeName]').val();
            var oldName = self.$root.find('input[name=creativeName]').data('old-name'); //原始值
            if (urlType == 'edit' && name == oldName) { //如果是编辑,且名字没有修改过,则不验证重复
                self._save();
            } else {
                self.checkName(function() {
                    self._save();
                });
            }
        }

        this._save = function() {
            var params = self.dialogParams.editType == 'create' ? self.getCreateParams() : self.getEditParams();
            if (params == 'no') {
                return;
            }
            var options = JSON.parse(params.options);
            if (options.festival) {
                if (options.festival.length == 0) {
                    delete options.festival;
                } else {
                    for (var i = 0; i < options.festival.length; i++) {
                        delete options.festival[i].categoryType;
                    }
                }

            }
            params.options = JSON.stringify(options);
            if (params.tags == null) {
                delete params.tags;
            }
            console.info(params);
            // return;
            ecCreativeTemplateBean.save(params, function(results) {
                self.$root.modal('hide');
                self.kit.alert_success(self.i18n('savedSuccessfully'));
                setTimeout(function() {
                    self.callback();
                }, 600)
            });
        }

        /**
         * { 检查 name是否唯一 }
         */
        this.checkName = function(checkNameCallback) {
            var name = self.$root.find('input[name=creativeName]').val();
            if (self.kit.isBlank(name)) {
                self.$root.find('input[name=creativeName]').testRemind(self.i18n('pleaseEnterAName'));
                self.$root.find('input[name=creativeName]').focus();
                return 'no';
            }
            var params = {
                name: name
            }
            ecCreativeTemplateBean.checkName(params, function(results) {
                if (results) {
                    self.$root.find('input[name=creativeName]').testRemind(self.i18n('duplicateName'));
                    self.$root.find('input[name=creativeName]').focus();
                    return;
                }
                checkNameCallback();
            });
        }

        /**
         * Gets the create parameters. 创建时候获取参数
         *
         * @return     {string}  The create parameters.
         */
        this.getCreateParams = function() {
            var name = self.$root.find('input[name=creativeName]').val();
            if (self.kit.isBlank(name)) {
                self.$root.find('input[name=creativeName]').testRemind(self.i18n('pleaseEnterAName'));
                self.$root.find('input[name=creativeName]').focus();
                return 'no';
            }
            var tags = self.$root.find('select.creativeTags').val();
            var feedId = self.kit.getCache('createMaterialStep1', 'feedId');
            var options = self.kit.getCache('createMaterialStep1', 'options');
            var templateId = self.kit.getCache('createMaterialStep2', 'ecTemplateId');
            var elements = self.kit.getCache('createMaterialStep2', 'elements');
            _.each(elements, function(ele) {
                ele.elementCategoryCode = ele.parentCode
                ele.isMajor = ele.major
            });

            var params = {
                saveType: 'new',
                name: name,
                tags: tags,
                options: JSON.stringify(options),
                feedId: feedId,
                thumbnail: self.dialogParams.previewImg,
                templateId: templateId,
                mainBgColor: self.kit.getCache('createMaterialStep2', 'mainBgColor'),
                joinBgColor: self.kit.getCache('createMaterialStep2', 'joinBgColor'),
                elements: elements
            }
            return params;
        }

        /**
         * Gets the edit parameters. 编辑复制的时候获取参数
         *
         * @return     {string}  The edit parameters.
         */
        this.getEditParams = function() {
            var name = self.$root.find('input[name=creativeName]').val();
            if (self.kit.isBlank(name)) {
                self.$root.find('input[name=creativeName]').testRemind(self.i18n('pleaseEnterAName'));
                self.$root.find('input[name=creativeName]').focus();
                return 'no';
            }
            var id = $('.layout-right').data('id');
            var tags = self.$root.find('select.creativeTags').val();
            var feedId = $('input[name=feed-name]').data('id');
            var options = localStorage.getItem('copyModule');
            var templateId = $('input[name=feed-name]').data('templateid');
            var elements = [];
            var $mainEle = $('input[name="main-element"]');
            var $lesserEle = $('input[name="lesser-element"]');
            var mEle = {
                context: $mainEle.val(),
                elementCategoryCode: $mainEle.attr('code'),
                fillValue: $mainEle.parent().find('input[name=fillValue]').val(),
                isMajor: $mainEle.attr('major'),
                major: $mainEle.attr('major'),
                parentCode: $mainEle.attr('code'),
                pid: $mainEle.attr('pid'),
                elementCode: $mainEle.attr('elementCode'),
                templateElementId: $mainEle.attr('templateElementId'),
                backgroundColor: $mainEle.attr('bgColor'),
                wordColor: $mainEle.attr('wordColor')
            }
            var lEle = {
                context: $lesserEle.val(),
                elementCategoryCode: $lesserEle.attr('code'),
                fillValue: $lesserEle.parent().find('input[name=fillValue]').val(),
                isMajor: $lesserEle.attr('major'),
                major: $lesserEle.attr('major'),
                parentCode: $lesserEle.attr('code'),
                pid: $lesserEle.attr('pid'),
                elementCode: $lesserEle.attr('elementCode'),
                templateElementId: $lesserEle.attr('templateElementId'),
                backgroundColor: $lesserEle.attr('bgColor'),
                wordColor: $lesserEle.attr('wordColor')
            }
            elements.push(mEle);
            elements.push(lEle);
            var saveType = '';
            var urlType = self.kit.getUrlParam('type');
            if (urlType == 'edit') {
                saveType = 'update';
            } else if (urlType == 'copy') {
                saveType = 'new';
            } else {
                self.kit.alert2(self.i18n('parameterError'));
                return 'no';
            }
            var bgColDiv = self.$root.find('#bg-div').find('.bgColorActive');
            if(bgColDiv.length)
                console.log(bgColDiv.data('color').substring(1));
            else
                console.log(self.$root.find('#bg-div').find('input').val());
            var params = {
                id: id,
                ecTemplateMaterielId: id,
                saveType: saveType,
                name: name,
                tags: tags,
                options: options,
                feedId: feedId,
                thumbnail: self.dialogParams.previewImg,
                templateId: templateId,
                elements: elements
            }
            return params;
        }

        this.i18n = function(key) {
            return I18N.getText('createMaterial', key)
        }
    }
    return me;
});